<?php
/**
 * jishupu-cms
 * @Author:技术铺
 * @Date:2021/11/22
 */

namespace App\Services;

use App\Models\InfoCategory;
use App\Services\InfoModelService;
use App\Services\DictionaryService;

/**
 * 信息栏目分类模块服务层
 *
 * Class InfoCategoryService
 * @package App\Services
 */
class InfoCategoryService
{

    /**
     * 获取上一级栏目树数据
     * @param $id // 当前栏目id
     * @params $is_disabled // 是否开启禁止 true/false
     * @return array
     */
    public static function getParentTree($id = 0, $is_disabled = true)
    {
        $filter = InfoCategory::select('id', 'parent_id', 'name', 'type', 'info_model_id')->orderBy('sort', 'asc')->orderBy('id', 'desc')->get();
        $selected_parent = ['id' => 0, 'name' => ''];
        $collectionKeyBy = collect($filter)->keyBy('id')->all();
        $pid = ($id > 0 && !empty($collectionKeyBy) && isset($collectionKeyBy[$id])) ? $collectionKeyBy[$id]['parent_id'] : 0;
        $collection = collect($filter)->map(function ($item) use ($id, $pid, &$selected_parent, $is_disabled) {
            $disabled = $is_disabled && ($id > 0 && $id == $item->id || in_array($item->type, array(2, 3, 4)));
            if ($item->id == $pid) {
                $selected_parent = ['id' => $item->id, 'name' => $item->name];
            }
            $model = InfoModelService::getModelById($item->info_model_id, ['id', 'name']);
            $type_name = DictionaryService::getItemName('infoCategoryTypeVar', $item->type);
            return ['id' => $item->id, 'parent_id' => $item->parent_id, 'name' => $item->name, 'disabled' => $disabled, 'model' => $model, 'type' => $item->type, 'type_name' => $type_name];
        });
        $parent_ids = [];
        if (!empty($collectionKeyBy)) {
            while ($pid > 0) {
                foreach ($collectionKeyBy as $id => $value) {
                    if ($pid == $id) {
                        array_unshift($parent_ids, $id);
                        $pid = $value['parent_id'];
                        if ($pid == 0) {
                            break;
                        }
                    }
                }
            }
        }
        $result = TreeService::make($collection);
        return ['items' => $result, 'parent' => $selected_parent, 'parent_ids' => $parent_ids];
    }

}
